package com.jbtm.mall.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.jbtm.mall.common.ServerResponse;
import com.jbtm.mall.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 *
 * 用于token安全性校验
 *
 */
public class AuthInterceptor implements HandlerInterceptor {
    private final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String key = request.getParameter("key");
        String token = request.getParameter("token");

        //免权限验证接口
        if (uri.contains("login") || uri.contains("upload") || uri.contains("api-docs") || uri.contains("raw") || uri.contains("wx")
                || uri.contains("wxinfo") || uri.contains("wximage") || uri.contains("wxreport")||uri.contains("updatephotos")) {
            return true;
        } else if (null != key && key.equals("zhaowh")) { //测试模式
            request.setAttribute("uid", TokenUtil.resolveToken(token));
            return true;
        }  else if (TokenUtil.authRequest(request.getParameterMap())) {
            request.setAttribute("uid", TokenUtil.resolveToken(token));
            return true;
        }

        //授权失败，返回错误信息
        response.setContentType("application/json; charset=UTF-8");
        response.setStatus(401); //未授权请求
        PrintWriter out = response.getWriter();
        out.print(JSONObject.toJSON(ServerResponse.errorMessage("非法请求")));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
